<?php 
/*
Copyright 2007 Dan Boitnott (dan@lclinux.org)

This file is part of phpTasks.

phpTasks is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

phpTasks is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with phpTasks; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/ 

session_start();

// Global Inits
require("global.php");

$CONFIG = array( "db_name" => "phptasks", 
                 "db_user" => "taskweb", 
                 "db_pass" => "taskweb", 
                 "sys_name" => "Task Master", 
                 "auth_method" => "html", 
                 "file_store" => null, 
                 "mime_file" => "/etc/apache2/conf/mime.types");
$CONFIG = parse_config_file("/etc/taskweb.conf", $CONFIG);

$conn = pg_connect("dbname=" . $CONFIG["db_name"] . " user=" . $CONFIG["db_user"] . " password=" . $CONFIG["db_pass"]);

$top_error = "";

// Security Concerns
if (!isset($_SESSION['sys_authd']))
	$_SESSION['sys_authd'] = false;

if (!isset($_SESSION['sys_authd_userid']))
	$_SESSION['sys_authd_userid'] = 0;

switch ($CONFIG["auth_method"]) {
case "html":
	if (!$_SESSION['sys_authd']) {
		if (is_array($HTTP_POST_VARS)) {
			foreach ($HTTP_POST_VARS as $k => $v) {
				if (($k != "login_username") && ($k != "login_password"))
					$login_hiddens[$k] = $v;
			}
   		}
		if (isset($HTTP_VARS["login_username"]) && isset($HTTP_VARS["login_password"])) {
			if ($login_r = fetchrow($conn, "users", "loginid='" . $HTTP_VARS["login_username"] . "' AND pwhash=md5('" . $HTTP_VARS["login_password"] . "')")) {
				$_SESSION['sys_authd'] = true;
				$_SESSION['sys_authd_userid'] = $login_r["userid"];
			} else {
				echo ($login_sql);
				html_login($REQUEST_URI, $login_hiddens, true);
				exit;
    			}
		} else {
			html_login($REQUEST_URI, $login_hiddens);
			exit;
   		}
	} else {
		$login_r = fetchrow($conn, "users", "userid=" . $_SESSION['sys_authd_userid']);
  	}
	break;
default:
	if ($login_r = fetchrow($conn, "users", "loginid='" . $REMOTE_USER . "'")) {
		$_SESSION['sys_authd'] = true;
		$_SESSION['sys_authd_userid'] = $login_r["userid"];
	} else {
		$_SESSION['sys_authd'] = false;
		echo ("You are not a registered user of the Tasks sub-system!");
		exit;
	}
}

if ($_SESSION['sys_authd'] && $login_r["may_logon"]) {
	$USER["userid"] = $login_r["userid"];
	$USER["name"] = $login_r["name"];
	$USER["modifyusers"] = $login_r["may_modifyusers"];
	$USER["modifytasks"] = $login_r["may_modifytasks"];
	$USER["viewalltasks"] = $login_r["may_viewalltasks"];
} else {
	$_SESSION['sys_authd'] = false;
	echo ("You are not authorized to access this system!");
	exit;
}

// Check File Storage
if (is_dir($CONFIG['file_store'])) {
  if (is_readable($CONFIG['file_store'])) {
    if (!is_writable($CONFIG['file_store'])) {
      $top_error .= "Error: File storage ('{$CONFIG['file_store']}') unwritable.<br/>";
    }
  } else {
    $top_error .= "Error: File storage ('{$CONFIG['file_store']}') unreadable.<br/>";
  }
} else {
  $top_error .= "Error: File storage ('{$CONFIG['file_store']}') does not exist or is not a directory.<br/>";
}

// Session Variable Initalization...
// Task List Variables
if (isset($HTTP_VARS["tl_userid"]))
	$_SESSION['tl_userid'] = $HTTP_VARS["tl_userid"];
elseif (!isset($_SESSION['tl_userid']))
	$_SESSION['tl_userid'] = $USER["userid"];

if (isset($HTTP_VARS["tl_view"])) {
	if ($HTTP_VARS["tl_view"] != $_SESSION['tl_view']) {
		$_SESSION['tl_view'] = $HTTP_VARS["tl_view"];
		if ($_SESSION['tl_view'] == "open")
			$_SESSION['tl_orderby'] = "priority";
		else
			$_SESSION['tl_orderby'] = "i_completed";
  	}
} elseif (!isset($_SESSION['tl_view']))
	$_SESSION['tl_view'] = "open";

if (isset($HTTP_VARS["tl_orderby"])) {
	$_SESSION['tl_orderby'] = $HTTP_VARS["tl_orderby"];
} elseif (!isset($_SESSION['tl_orderby']))
	$_SESSION['tl_orderby'] = ($_SESSION['tl_view'] == "open" ? "priority" : "completed_on");

function std_header($title) {
  global $top_error
?>
	<html>
	<head>
	<link href='global.css' rel='STYLESHEET' type='text/css'>
	<title><?=$title?></title>
	</head>
	<body>
<?php if ($top_error != "") { ?>
        <table align='center' width='100%' class='border: 1px solid black'>
	<tr><td bgcolor="#ff9999" align="left" valign="top">
        <?=$top_error ?>
        </td></tr></table>
<?php 
  }
}

function std_footer() {
?>
	</body>
	</html>
<?php
}

function priority_color_old($p) {
	switch ($p) {
	case 1:
		$ret = "#ff7070";
		break;
  	case 2:
		$ret = "#ffc0c0";
		break;
  	case 3:
		$ret = "#ffffc0";
		break;
  	case 4:
		$ret = "#70ff70";
		break;
  	case 5:
		$ret = "#c0ffco";
  		break;
    	default:
		$ret = "#c0c0c0";
  	}
	return $ret;
}

function priority_color($p) {
        return priority_color_new($p, 1, 10);
}

function priority_color_new($p, $min, $max) {
	$gl = hexdec("a0");
        $ml = hexdec("ff");
	$c_min = array($ml, $gl, $gl);
        $c_mid = array($ml, $ml, $gl);
	$c_max = array($gl, $ml, $gl);

	$c_p = "";
	for ($x = 0; $x < 3; $x++) {
		$c_a = dechex(floor(dither($p, $min, $max, $c_min[$x], $c_max[$x], $c_mid[$x])));
		if (strlen($c_a) < 2)
			$c_a = "0" . $c_a;
		$c_p .= $c_a;
	}

	$ret = "#" . $c_p;

	return $ret;
}

function dither($p, $min, $max, $c_min, $c_max, $c_mid = "undefined") {
        if ($c_mid <> "undefined") {
                if ($p < ($min + (($max - $min) / 2))) {
                        $c_max = $c_mid;
                        $max = $max - (($max - $min) / 2);
                } else {
                        $c_min = $c_mid;
                        $min = $min + (($max - $min) / 2);
                }
        }
        if (($max - $min) > 0)
	        return $c_min + (($p - $min) * (($c_max - $c_min) / ($max - $min)));
        else
                return $c_max;
}

function sort_by_selector($prefix, $value, $method = "ASC") {
?>
	<select name='<?=$prefix?>_field'>
		<option <?=($value == "created") ? "selected" : "" ?> value='created'>Assignment Date</option>
		<option <?=($value == "completed") ? "selected" : "" ?> value='completed'>Completion Date</option>
		<option <?=($value == "priority") ? "selected" : "" ?> value='priority'>Priority</option>
		<option <?=($value == "taskid") ? "selected" : "" ?> value='taskid'>Task ID</option>
		<option <?=($value == "title") ? "selected" : "" ?> value='title'>Title</option>
	</select>
	<select name='<?=$prefix?>_method'>
		<option <?=($method == "ASC") ? "selected" : "" ?> value='ASC'>Ascending</option>
		<option <?+($method == "DESC") ? "selected" : "" ?> value='DESC'>Descending</option>
	</select>
<?php
}

function html_login($redir, $hiddens = false, $badtry = false) {
	std_header("Login");
	echo ("<form action='" . $redir . "' method='POST'>");
	if ($hiddens) {
		foreach ($hiddens as $k => $v)
			echo ("<input type=hidden name='$k' value='$v'>");
   	}
?>
	<table border='0'>
	<tr>
		<td colspan=2 align='left'><big><strong>Login:</strong></big></td>
  	</tr>
	<?php if ($badtry) { ?>
		<tr>
			<td colspan=2 align='left'><strong>Bad username or password</strong></td>
   		</tr>
     	<?php } ?>
	<tr>
		<td align='right'><small><strong>Username:</strong></small></td>
		<td align='left'><input type=text name='login_username'></td>
  	</tr><tr>
		<td align='right'><small><strong>Password:</strong></small></td>
		<td align='left'><input type=password name='login_password'></td>
  	</tr><tr>
		<td></td>
		<td align='left'><input type=submit value="Ok"/></td>
  	</tr>
	</table>
	</form>
<?php
	std_footer();
}

function taskastext($conn, $taskid) {
	$sql = "SELECT * FROM task_list WHERE taskid=" . $taskid;
	$res = pg_exec($conn, $sql);
	if($r = get_row($res, 0)) {
		$ret = "Task #" . $r["taskid"] . ": " . $r["title"] . "\n";
		if ($r["completed"])
			$ret .= "Status: Completed " . $r["completed"] . "\n";
		else
			$ret .= "Open\n";
   		$ret .= "Assigned By: " . $r["assigned_by"] . "\n";
		$ret .= "Assigned To: " . $r["assigned_to_name"] . "\n";
		$ret .= "Description:\n";
		$ret .= $r["description"] . "\n\n";
		$ret .= "Log:\n";
		$sql = "SELECT * FROM tasklog_list WHERE taskid=" . $taskid . " ORDER BY created";
		$res = pg_exec($conn, $sql);
		$rc = pg_numrows($res);
		if ($rc > 0) {
			for ($rnum = 0; $rnum < $rc; $rnum++) {
				$l = get_row($res, $rnum, "daydatetime");
				$ret .= $l["user"] . " - " . $l["created"] . "\n";
				$ret .= $l["entry"] . "\n";
			}
		} else
			$ret .= "No Entries";
	} else
		$ret = false;
  	return $ret;
}
?>
